package ltd.hyangyang.vegetable.utils;

import io.minio.*;
import io.minio.errors.MinioException;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

public class MinIOUtils {
    //上传文件，返回文件路径
    public static String fileUpload(MinIOProperties minIOProperties, MultipartFile file)
            throws IOException, NoSuchAlgorithmException, InvalidKeyException {
        InputStream inputStream = file.getInputStream();
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String originalFilename = file.getOriginalFilename();
        String format = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = uuid+format;
        try {
            // Create a minioClient with the MinIO server playground, its access key and secret key.
            MinioClient minioClient =
                    MinioClient.builder()
                            .endpoint(minIOProperties.getAddr())
                            .credentials(minIOProperties.getAccessKey(), minIOProperties.getSecretKey())
                            .build();

            // Make 'asiatrip' bucket if not exist.
            boolean found =
                    minioClient.bucketExists(BucketExistsArgs.builder().bucket(minIOProperties.getBucketName()).build());
            if (!found) {
                // Make a new bucket called 'asiatrip'.
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minIOProperties.getBucketName()).build());
            } else {

            }

            // Upload '/home/user/Photos/asiaphotos.zip' as object name 'asiaphotos-2015.zip' to bucket
            // 'asiatrip'.
            String src = minIOProperties.getAddr()+"/"+minIOProperties.getBucketName()+"/classification/"+fileName;
//            minioClient.uploadObject(
//                    UploadObjectArgs.builder()
//                            .bucket(minIOProperties.getBucketName())
//                            .object(filePath)
//                            .filename("/classification/"+fileName)
//                            .build());
            minioClient.putObject(
                    PutObjectArgs.
                            builder().
                            bucket(minIOProperties.getBucketName()).
                            object("/classification/"+fileName).
                            stream(inputStream,file.getSize(),-1).
                            build()
            );
            return src;
        } catch (MinioException e) {
            System.out.println("Error occurred: " + e);
            System.out.println("HTTP trace: " + e.httpTrace());
        }
        return null;
    }
}
